<template>
  <view>
    <swiper
      class="swiper-box"
      :circular="circular"
      :indicator-dots="true"
      :autoplay="autoplay"
      :interval="interval"
      @change="swiperChange"
    >
      <swiper-item v-for="(videoUrl, index) in videolist" :key="index">
        <view>
          <video
            :id="`video_${index}`"
            :show-center-play-btn="false"
            :show-fullscreen-btn="true"
            :loop="false"
            :autoplay="false"
            :show-mute-btn="true"
            :enable-progress-gesture="false"
            :src="videoUrl"
            object-fit="contain"
          ></video>
        </view>
      </swiper-item>
      <swiper-item v-for="(imageUrl, index) in imagelist" :key="index">
        <view>
          <image :mode="mode" :src="imageUrl" @click="preview(imagelist, index)"></image>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script lang="ts" setup>
  import { ref, getCurrentInstance } from 'vue';
  import { getFileType } from '@/utils/file';
  import type { PropType } from 'vue';

  const props = defineProps({
    list: { type: Array as PropType<string[]>, default: [] },
    mode: { type: String, default: 'widthFix' },
    height: { type: Number, default: 800 },
    maxHeight: { type: Number, default: 1000 },
    preview: { type: Boolean, default: false },
    autoplay: { type: Boolean, default: true },
    interval: { type: Number, default: 8000 },
    circular: { type: Boolean, default: true },
  });

  const _this = getCurrentInstance();
  const _height = props.height + 'rpx';
  const _maxHeight = props.maxHeight + 'rpx';

  const imagelist = ref<string[]>([]);
  const videolist = ref<string[]>([]);
  let ext = '';
  let players = [] as any;

  props.list.forEach((url, idx) => {
    ext = getFileType(url);
    if (!ext || ext == 'image') {
      imagelist.value.push(url);
    } else {
      videolist.value.push(url);
      players.push(uni.createVideoContext(`video_${idx}`, _this));
    }
  });

  // swiper滑动
  const swiperChange = () => {
    if (players.length > 0) {
      players.forEach((player: any) => {
        player.pause();
      });
    }
  };

  // 图片预览
  const preview = (urls: string[], index: number) => {
    if (!props.preview) return false;
    uni.previewImage({ current: index, urls: urls });
  };
</script>

<style lang="scss" scoped>
  .swiper-box {
    height: v-bind(_height);
    max-height: v-bind(_maxHeight);

    image {
      width: 100%;
      max-height: v-bind(_maxHeight);
    }

    video {
      width: 100%;
      height: v-bind(_height);
      max-height: v-bind(_maxHeight);
    }
  }
</style>
